package cn.it.shop.service.impl;

import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.math.BigInteger;
import java.util.List;

import javax.annotation.Resource;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import cn.it.shop.service.BaseService;


@Service("baseService")
@Lazy(true)
public class BaseServiceImpl<T> implements BaseService<T> {
	
	@Resource
	private SessionFactory sessionFactory;
	
	private Class clazz;//存储了当前操作类型,先假设后实现
	
	
	public BaseServiceImpl() {
//		System.out.println("this表示当前调用构造方法的对象"+this);
//		System.out.println("获取当前this对象的父类的信息(包括泛型信息)"+this.getClass().getGenericSuperclass());
		//获取泛型信息
		ParameterizedType type = (ParameterizedType)this.getClass().getGenericSuperclass();
		clazz = (Class)type.getActualTypeArguments()[0];
	}

	public Session getSession() {
		//从当前线程中获取session,如果没有则创建一个session
		//return sessionFactory.getCurrentSession();
		org.hibernate.classic.Session session = sessionFactory.getCurrentSession();
		return session;
	}
	
	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}
	
	@Override
	public void save(T t) {
		getSession().save(t);
		System.out.println("新增数据成功");
	}

	@Override
	public void update(T t) {
		getSession().update(t);
		System.out.println("修改数据成功");

	}

	@Override
	public void delete(Object id) {
		String hql = "DELETE " + clazz.getSimpleName()+" WHERE id=:id";
		getSession().createQuery(hql)
			.setLong("id",(Long) id)
			.executeUpdate();
	}

	@Override
	public T get(Object id) {
		return (T)getSession().get(clazz,(Serializable) id);
	}

	
	@Override
	public List<T> query() {
		String hql = "FROM " + clazz.getSimpleName();
		return getSession().createQuery(hql).list();
	}

	public SessionFactory getSessionFactory() {
		return sessionFactory;
	}

	
}
